package SaveServlet.admin;

import com.lyq.bean.service.E_Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/AddRequiredCourse_Servlet")
public class AddRequiredCourse_Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public AddRequiredCourse_Servlet() {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取必修课程信息
        String[] requiredCourses = request.getParameterValues("requiredCourses");
        String studentNo = request.getParameter("studentNo");
        
        String message = "";
        
        if (requiredCourses != null && requiredCourses.length > 0 && studentNo != null && !studentNo.isEmpty()) {
            // 为学生添加必修课程
            int successCount = 0;
            for (String courseNo : requiredCourses) {
                // 检查是否已选
                if (!(new E_Service()).isCourseElected(courseNo, studentNo)) {
                    // 检查时间冲突
                    if (!(new E_Service()).hasTimeConflict(courseNo, studentNo)) {
                        // 添加课程
                        String result = (new E_Service()).elect_C(courseNo, studentNo, "");
                        if (result == null || result.isEmpty()) {
                            successCount++;
                        }
                    }
                } else {
                    successCount++; // 已选则计为成功
                }
            }
            
            message = "成功为学生 " + studentNo + " 添加了 " + successCount + " 门必修课程！";
        } else {
            message = "参数错误，添加必修课程失败！";
        }
        
        request.getSession().setAttribute("message", message);
        request.getSession().setAttribute("url", "jsp/manager/M_Home.jsp");
        request.getRequestDispatcher("Message.jsp").forward(request, response);
    }
}